<template>
  <el-form ref="deptForm" :rules="rules" :model="form" label-width="120px">
    <el-form-item label="部门名称" prop="name">
      <el-input
        v-model="form.name"
        style="width: 80%"
        placeholder="1-50个字符"
      />
    </el-form-item>
    <el-form-item label="部门编码" prop="code">
      <el-input
        v-model="form.code"
        style="width: 80%"
        placeholder="1-50个字符"
      />
    </el-form-item>
    <el-form-item label="部门负责人" prop="manager">
      <el-select v-model="form.manager" style="width: 80%" placeholder="请选择">
        <el-option
          v-for="item in employees"
          :key="item.id"
          :value="item.username"
          :label="item.username"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="部门介绍" prop="introduce">
      <el-input
        v-model="form.introduce"
        style="width: 80%"
        placeholder="1-300个字符"
        type="textarea"
        :rows="3"
      />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" size="small" @click="hSubmit">确定</el-button>
      <el-button size="small" @click="$emit('close')">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { getEmployeeSimple } from '@/api/employees'
import {
  addDepartments,
  getDepartDetail,
  updateDepartments
} from '@/api/departments'

export default {
  // 接受父组件的数据
  props: {
    pid: {
      required: true,
      type: String
    },
    isEdit: {
      required: true,
      type: Boolean
    },
    valiList: {
      required: true,
      type: Array
    }
  },
  data() {
    // code校验规则
    const validCode = (rule, value, callback) => {
      // rule     : 当前的规则
      // value    : 被校验的值
      // callback : 回调
      //      如果通过了规则检验，直接调用callback()
      //      如果没有通过规则检验，调用callback(错误对象，在错误对象中说明原因)
      //      callback(new Error('错误说明'))
      let res = this.valiList.map((item) => item.code)
      // 编辑状态
      if (this.isEdit) {
        const curCode = this.valiList.find((item) => (item.id === this.pid))
        const curId = curCode.code
        res = this.valiList.filter((item) => item.code !== curId)
      }

      if (res.includes(value)) {
        callback(new Error(value + '已存在'))
      } else {
        callback()
      }
    }
    // name校验规则
    const validName = (rule, value, callback) => {
      let existNameList = this.valiList
        .filter((item) => item.pid === this.pid)
        .map((item) => item.name)
      // 编辑状态
      if (this.isEdit) {
        const res = this.valiList.find((item) => item.id === this.pid).pid
        existNameList = this.valiList
          .filter((item) => item.pid === res && item.id !== this.pid)
          .map((item) => item.name)
      }
      if (existNameList.includes(value)) {
        callback(new Error(value + '已存在'))
      } else {
        callback()
      }
    }
    return {
      form: {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      },
      // 保存下拉员工数据
      employees: [],
      // 校验规则
      rules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          {
            min: 1,
            max: 50,
            message: '部门名称要求1-50个字符',
            trigger: 'blur'
          },
          { validator: validName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: 'blur' },
          {
            min: 1,
            max: 50,
            message: '部门编码要求1-50个字符',
            trigger: 'blur'
          },
          { validator: validCode, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '部门负责人不能为空', trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: 'blur' },
          {
            min: 1,
            max: 300,
            message: '部门介绍要求1-300个字符',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created() {
    // 添加
    this.loadEmployee()
    // 编辑
    // if (this.isEdit) {
    // this.loadDetail()
    // }
  },
  methods: {
    // 下拉员工数据获取
    async loadEmployee() {
      const res = await getEmployeeSimple()
      // console.log(res)
      this.employees = res.data
    },
    // 添加
    async doAdd() {
      const d = { ...this.form, pid: this.pid }
      await addDepartments(d)
      // console.log(res)
      // 子向父传
      this.$emit('success')
    },
    // 编辑保存更新
    async doEdit() {
      await updateDepartments(this.form)
      // console.log(res)
      // 子向父传
      this.$emit('success')
    },
    hSubmit() {
      this.$refs.deptForm.validate((valid) => {
        if (valid) {
          this.isEdit ? this.doEdit() : this.doAdd()
        }
      })
    },
    // 编辑
    async loadDetail() {
      const res = await getDepartDetail(this.pid)
      // console.log(res)
      this.form = res.data
    },
    // 清空表单验证效果
    hCancel() {
      this.$refs.deptForm.resetFields()
    }
  }
}
</script>

<style></style>
